﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using System.IO;
using BRM.DataObjects;
using BRM.Business;
using System.Collections;
using System.Configuration;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
namespace BRM.GUI
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        public MainForm()
        {
            InitializeComponent();
            //AQFramework.Configurations config = new AQFramework.Configurations("BRM.config", true);
            //config.WriteAppSettings("Name", "BRM13");
            //config.WriteAppSettings("Default_path", @"D:\Study\Project\Test");
            //config.WriteAppSettings("Pass", "1234");
            //config.WriteAppSettings("Server_name", @"CHICKEN-PC\SQLEXPRESS");
            //config.WriteAppSettings("User_name", "sa");
            //config.WriteAppSettings("User_pass", "123456");
            //config.WriteAppSettings("DB_name", "QLMATHANG");
            //config.WriteAppSettings("Auto_date", "Friday");
            //config.WriteAppSettings("Auto_time", "6:00 AM");
            
            AQFramework.Configurations conf = new AQFramework.Configurations("BRM.config", true);
            txtBackupFileName.Text = conf.ReadAppSettings("Name");

            txtBackupFilePath.Text = conf.ReadAppSettings("Default_path");
            txtBackupPassword.Text = conf.ReadAppSettings("Pass");

            VERSIONMANAGEMENT vm = new VERSIONMANAGEMENT();
            AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(vm, Application.StartupPath + "\\auto_backuplist.xml");
            FileInfo vermanagexml = new FileInfo(Application.StartupPath + "\\versionmanagement.xml");
            if (vermanagexml.Exists == false)
            {
                VERSIONMANAGEMENT vm1 = new VERSIONMANAGEMENT();
                AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(vm1, Application.StartupPath + "\\versionmanagement.xml");
            }
            txtBackupDB_FileName.Text = conf.ReadAppSettings("Name");
            txtBackupDB_FilePath.Text = conf.ReadAppSettings("Default_path");

            txtBackupDB_Database.Text = conf.ReadAppSettings("DB_name");
            txtBackupDB_ServerName.Text = conf.ReadAppSettings("Server_name");
            txtBackupDB_UserName.Text = conf.ReadAppSettings("User_name");
            txtBackupDB_UserPass.Text = conf.ReadAppSettings("User_pass");

            txtSetting_Filename.Text = conf.ReadAppSettings("Name");
            txtSetting_Path.Text = conf.ReadAppSettings("Default_path");
            txtSetting_Pass.Text = conf.ReadAppSettings("Pass");

            txtSetting_Sername.Text = conf.ReadAppSettings("Server_name");
            txtSetting_Username.Text = conf.ReadAppSettings("User_name");
            txtSetting_Userpass.Text = conf.ReadAppSettings("User_pass");
            txtSetting_Dbname.Text = conf.ReadAppSettings("DB_name");

        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {
            tmAutoList.Enabled = true;
            tmBackup.Enabled = true;
        }

        private void simpleButton2_Click_1(object sender, EventArgs e)
        {
            FolderBrowserDialog fbrowse = new FolderBrowserDialog();
            DialogResult dresult = fbrowse.ShowDialog();
            if (dresult == DialogResult.Cancel) return;

            txtBackupPathShow.Text = fbrowse.SelectedPath;
            string sPath = txtBackupPathShow.Text;

            TreeNode rootNode = new TreeNode(sPath);

            trvBackupChoose.Nodes.Add(rootNode);
            FillNode(rootNode);
            trvBackupChoose.Nodes[0].Expand();
        }

        private static void FillNode(TreeNode node)
        {
            DirectoryInfo dir = new DirectoryInfo(node.FullPath);

            //Exception có khả năng xảy ra ở bước này
            foreach (DirectoryInfo dirItem in dir.GetDirectories())
            {
                TreeNode newNode = new TreeNode(dirItem.Name);
                newNode.Tag = "Folder";
                newNode.ImageIndex = 1;
                node.Nodes.Add(newNode);
                newNode.Nodes.Add("*");
            }

            foreach (FileInfo fileItem in dir.GetFiles())
            {
                TreeNode newNode = new TreeNode(fileItem.Name);
                newNode.Tag = "File";
                if (fileItem.Extension == ".docx" || fileItem.Extension == ".doc") newNode.ImageIndex = 2;
                else if (fileItem.Extension == ".xlsx" || fileItem.Extension == ".xls") newNode.ImageIndex = 3;
                else if (fileItem.Extension == ".ppt" || fileItem.Extension == ".pptx") newNode.ImageIndex = 4;
                else if (fileItem.Extension == ".pdf") newNode.ImageIndex = 6;
                else if (fileItem.Extension == ".rar" || fileItem.Extension == ".zip") newNode.ImageIndex = 8;
                else if (fileItem.Extension == ".jpg" || fileItem.Extension == ".gif" || fileItem.Extension == ".png") newNode.ImageIndex = 7;
                else newNode.ImageIndex = 5;

                //newNode.SelectedImageIndex = 5;
                node.Nodes.Add(newNode);
            }
        }

        private void Do_backup()
        {
            string sVersion = DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString();
            string sNewpath = txtBackupFileName.Text + "-" + sVersion;
            BackupController bkc = new BackupController();
            bkc.Backup(txtBackupFileName.Text + "-" + sVersion, txtBackupFilePath.Text, txtBackupPassword.Text, txtBackupFilePath.Text + "\\" + sNewpath + "info.xml");
            //MessageBox.Show("Done");         
        }

        ProgressBar pbProgress;
        private void simpleButton3_Click(object sender, EventArgs e)
        {

            DirectoryInfo fbackup = new DirectoryInfo(txtBackupFilePath.Text);
            DriveInfo dinfo = new DriveInfo(fbackup.Root.ToString());
            lblDirectoryName.Text = fbackup.Root.ToString();
            long a = (dinfo.TotalSize) / (1024 * 1024 * 1024);
            progressBarControl1.Properties.Maximum = Convert.ToInt32(a);
            long la = (dinfo.TotalFreeSpace) / (1024 * 1024 * 1024);
            int ifree = Convert.ToInt32(la);

            lblFreeSpace.Text = ifree.ToString() + " MB";
            progressBarControl1.Position = progressBarControl1.Properties.Maximum - ifree;

            lblInfo_Date.Text = DateTime.Now.ToShortDateString();
            lblInfo_fName.Text = txtBackupFileName.Text;
            lblInfo_Path.Text = txtBackupFilePath.Text;

            string sDate = DateTime.Now.ToShortDateString();
            string sName = txtBackupFileName.Text;
            string sPath = txtBackupFilePath.Text;
            string sPassword = txtBackupPassword.Text;
            string sBkdate = null;
            string sBktime = null;
            if (Check_Info(sName, sPath, sPassword) == true)
            {
                //Do_backup()
                if (chkBackupAto.Checked == true)
                {
                    if (radBackup_Weekly.Checked == true)
                    {
                        sBkdate = deBackupAutoDate.Text;
                        sBktime = teBackupAutoTime.Text;
                        lblInfo_Descript.Text = "Backup hằng tuần vào " + sBkdate + " vào lúc " + sBktime;
                    }
                    if (radBackup_Daily.Checked == true)
                    {
                        sBkdate = "";
                        sBktime = teBackupAutoTime.Text;
                        lblInfo_Descript.Text = "Backup hằng ngày vào lúc " + sBktime;
                    }
                }
                else if (chkBackupAto.Checked == false)
                {
                    sBkdate = "";
                    sBktime = "";
                }


                BackupController bkc = new BackupController();

                string sVersion = DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString();
                string sNewpath = txtBackupFileName.Text + "-" + sVersion;

                ArrayList arrFile = new ArrayList();
                ArrayList arrFolder = new ArrayList();
                if (lsvBackupFileList.CheckedItems.Count > 0)
                {
                    foreach (ListViewItem childNode in lsvBackupFileList.Items)
                    {
                        if (childNode.Checked)
                        {
                            if (childNode.Tag == "File")
                                arrFile.Add(childNode.SubItems[1].Text);

                            else
                                arrFolder.Add(childNode.SubItems[1].Text);
                        }
                    }


                    string sDateinfo = DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/" + DateTime.Now.Year.ToString();
                    string sNameinfo = txtBackupFileName.Text;
                    string sPass = txtBackupPassword.Text;
                    string sPathinfo = txtBackupFilePath.Text;
                    string sBkdateinfo = deBackupAutoDate.Text;
                    string sBktimeinfo = teBackupAutoTime.Text;

                    FileInfo info = new FileInfo(txtBackupFilePath.Text + "\\" + sNewpath + "info.xml");
                    if (info.Exists == false)
                    {
                        pbProgress = new ProgressBar(lsvBackupFileList.CheckedItems.Count);
                        pbProgress.Show(this);
                        bkc.Create_info(arrFile, arrFolder, sDateinfo, sNameinfo, sPathinfo, sPass, sBkdateinfo, sBktimeinfo, txtBackupFilePath.Text + "\\" + sNewpath + "info.xml");
                        bkc.Update_Version(sName, sDate, sPath, sPassword, sBkdate, sBktime, Application.StartupPath + "\\versionmanagement.xml");
                        Thread t = new Thread(new ThreadStart(Do_backup));
                        tInfo.SelectedTabPage = xtraTabPage1;
                        t.Start();
                    }
                    else if (info.Exists == true)
                    {
                        DialogResult result = MessageBox.Show("File backup đang tồn tại. Bạn có muốn tạo trên file đã có?", "Xác nhận Backup", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                        {
                            pbProgress = new ProgressBar(lsvBackupFileList.CheckedItems.Count);
                            pbProgress.Show(this);
                            bkc.Create_info(arrFile, arrFolder, sDateinfo, sNameinfo, sPathinfo, sPass, sBkdateinfo, sBktimeinfo, txtBackupFilePath.Text + "\\" + sNewpath + "info.xml");
                            Thread t = new Thread(new ThreadStart(Do_backup));
                            tInfo.SelectedTabPage = xtraTabPage1;
                            t.Start();
                        }
                        else if (result == DialogResult.No)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Chưa chọn file/folder cần backup", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        string sBkpath;
        string sBkname;
        ArrayList bkinfolist;
        private void Do_Restore()
        {


            //string bkinfo = bkpath + "\\" + bkname + "info.xml";
            string sBkpass = null;
            string sBkinfo = sBkpath + "\\" + sBkname + "info.xml";
            VERSION vBkup = AQFramework.Utilities.Serializer<VERSION>.Load(sBkinfo);
            foreach (versionItems vi in vBkup.versions)
            {
                sBkpass = vi.sPassword;
            }


            RestoreController rc = new RestoreController();
            rc.Restore(sBkname, sBkpath, sBkinfo, bkinfolist, sBkpass);
            //pbProgress.Close();
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            if (lvRestore_FileList.CheckedItems.Count > 0)
            {
                pbProgress = new ProgressBar(lvRestore_FileList.CheckedItems.Count);
                pbProgress.Show(this);

                Thread t1 = new Thread(new ThreadStart(Do_Restore));
                bkinfolist = new ArrayList();
                ListViewItem lititem =new ListViewItem();
                for (int i = 0; i < lvRestore_FileList.Items.Count; i++)
                {
                    if (lvRestore_FileList.Items[i].Checked)
                    {
                        bkinfolist.Add(lvRestore_FileList.Items[i].ToString());
                    }
                }
                this.Text = lvRestore_FileList.CheckedItems.Count.ToString();                 
                sBkpath = lvRestore_BackupList.SelectedItems[0].SubItems[1].Text;
                sBkname = lvRestore_BackupList.SelectedItems[0].SubItems[0].Text + "-" + lvRestore_BackupList.SelectedItems[0].SubItems[3].Text;
                lblInfoRestore_fName.Text = lvRestore_BackupList.SelectedItems[0].SubItems[0].Text;
                lblInfoRestore_Date.Text = DateTime.Now.ToShortDateString();
                lblInfoRestore_Version.Text = lvRestore_BackupList.SelectedItems[0].SubItems[3].Text;
                tInfo.SelectedTabPage = xtraTabPage1;
                t1.Start();
            }
            else
            {
                MessageBox.Show("Chưa lựa chọn file/folder cần restore", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSetting_BackupFile.Checked == true)
            {
                txtSetting_Filename.Enabled = true;
                txtSetting_Pass.Enabled = true;
            }
            else
            {
                txtSetting_Filename.Enabled = false;
                txtSetting_Pass.Enabled = false;
            }
        }

        private void checkEdit2_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSetting_BackupDB.Checked == true)
            {
                txtSetting_Sername.Enabled = true;
                txtSetting_Userpass.Enabled = true;
                txtSetting_Dbname.Enabled = true;
                txtSetting_Username.Enabled = true;
            }
            else
            {
                txtSetting_Sername.Enabled = false;
                txtSetting_Userpass.Enabled = false;
                txtSetting_Dbname.Enabled = false;
                txtSetting_Username.Enabled = false;
            }

        }

        private void checkEdit3_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSetting_AutoBackup.Checked == true)
            {
                deSetting_Autodate.Enabled = true;
                teSetting_Autotime.Enabled = true;
                chkSetting_Weekly.Enabled = true;
                chkSetting_daily.Enabled = true;
            }
            else
            {
                deSetting_Autodate.Enabled = false;
                teSetting_Autotime.Enabled = false;
                chkSetting_Weekly.Enabled = false;
                chkSetting_daily.Enabled = false;
            }
        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Nodes[0].Text == "*")
            {
                e.Node.Nodes.Clear();
                FillNode(e.Node);
            }
        }

        private void CheckAllChildNodes(TreeNode treeNode, bool bCheck)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                node.Checked = bCheck;
                if (node.Nodes.Count > 0)
                {
                    // If the current node has child nodes, call the CheckAllChildsNodes method recursively.
                    this.CheckAllChildNodes(node, bCheck);
                }
            }
        }
        private void AddList(TreeViewEventArgs e)
        {
            BackupController bkc = new BackupController();
            ListViewItem Item = null;
            if (e.Node.Text.Contains(@"\"))
            {
                FileInfo root = new FileInfo(e.Node.Text);
                Item = new ListViewItem(root.Name);
            }
            else Item = new ListViewItem(e.Node.Text);
            Item.Tag = e.Node.Tag;
            Item.SubItems.Add(e.Node.FullPath);

            try
            {
                if (e.Node.Tag == "File")
                {
                    FileInfo fnode = new FileInfo(e.Node.FullPath.ToString());
                    Item.SubItems.Add(fnode.Length.ToString());
                    Item.SubItems.Add(fnode.Extension.ToString());
                }
                else
                {
                    DirectoryInfo dir = new DirectoryInfo(e.Node.FullPath);
                    string sdirsize = bkc.GetDirectorySize(dir).ToString();
                    Item.SubItems.Add(sdirsize);
                }
            }
            catch (Exception k)
            {
                DriveInfo c = new DriveInfo(e.Node.FullPath);
                Item.SubItems.Add(c.TotalSize.ToString());
            }
            lsvBackupFileList.Items.Add(Item);
            Item.Checked = true;
        }

        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Checked == true)
            {
                if (e.Node.Nodes.Count > 0)
                {
                    CheckAllChildNodes(e.Node, true);
                }
            }
            if (e.Node.Checked == false)
            {
                if (e.Node.Nodes.Count > 0)
                {
                    CheckAllChildNodes(e.Node, false);
                }
            }
            
            if(e.Node.Text.Contains(@"\") && e.Node.Checked==true)
            {
                AddList(e);
            }
            else if (e.Node.Text.Contains(@"\")&&e.Node.Checked == false)
            {
                foreach (ListViewItem item in lsvBackupFileList.Items)
                {
                    if (item.SubItems[1].Text == e.Node.FullPath)
                        lsvBackupFileList.Items.Remove(item);
                }
            }
            else if (e.Node.Parent.Checked == false)
            {
                if (e.Node.Checked && e.Node.Text != "*")
                {
                    AddList(e);
                }
                else
                {
                    foreach (ListViewItem item in lsvBackupFileList.Items)
                    {
                        if (item.SubItems[1].Text == e.Node.FullPath)
                            lsvBackupFileList.Items.Remove(item);
                    }

                }
            }
            else
            {
                if (e.Node.Checked == false)
                {
                    e.Node.Parent.Checked = false;
                    CheckAllChildNodes(e.Node.Parent, true);
                    e.Node.Checked = false;
                }
            }
        }

        private void listView1_MouseDoubleClick_1(object sender, MouseEventArgs e)
        {
            if (lsvBackupFileList.SelectedItems.Count > 0)
            {
                try
                {
                    Process.Start(lsvBackupFileList.SelectedItems[0].SubItems[1].Text);
                }
                catch (InvalidOperationException ex)
                {
                    //Xử lý ngoại lệ

                }
                catch (ArgumentNullException ex)
                {
                    //Xử lý ngoại lệ

                }
                catch (Win32Exception ex)
                {
                    //Xử lý ngoại lệ
                }
            }
        }


        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            FolderBrowserDialog fdbr = new FolderBrowserDialog();
            DialogResult dresult = fdbr.ShowDialog();
            if (dresult == DialogResult.Cancel) return;
            txtBackupFilePath.Text = fdbr.SelectedPath;
        }

        private void checkEdit4_CheckedChanged(object sender, EventArgs e)
        {
            if (chkBackupModify.Checked == true)
            {
                txtBackupFileName.Enabled = true;
                txtBackupPassword.Enabled = true;
            }
            else
            {
                txtBackupFileName.Enabled = false;
                txtBackupPassword.Enabled = false;
            }
        }

        private void checkEdit5_CheckedChanged(object sender, EventArgs e)
        {
            if (chkBackupAto.Checked == true)
            {
                deBackupAutoDate.Enabled = true;
                teBackupAutoTime.Enabled = true;
                radBackup_Weekly.Enabled = true;
                radBackup_Daily.Enabled = true;
            }
            else
            {
                deBackupAutoDate.Enabled = false;
                teBackupAutoTime.Enabled = false;
                radBackup_Weekly.Enabled = false;
                radBackup_Daily.Enabled = false;
            }
        }

        private void simpleButton10_Click_1(object sender, EventArgs e)
        {
            SettingController sc = new SettingController();
            if (chkSetting_BackupFile.Checked == true && Check_Info(txtSetting_Filename.Text, txtSetting_Path.Text, txtSetting_Pass.Text) == true)
            {
                sc.sName = txtSetting_Filename.Text;
                sc.sPath = txtSetting_Path.Text;
                sc.sPass = txtSetting_Pass.Text;
            }
            if (chkSetting_BackupDB.Checked == true && Check_DBInfo(txtSetting_Sername.Text, txtSetting_Username.Text, txtSetting_Userpass.Text, txtSetting_Dbname.Text, null, null) == true)
            {
                sc.sSvname = txtSetting_Sername.Text;
                sc.sSvpass = txtSetting_Userpass.Text;
                sc.sDbname = txtSetting_Dbname.Text;
                sc.sUsername = txtSetting_Username.Text;
            }
            if (chkSetting_AutoBackup.Checked == true)
            {
                if (chkSetting_daily.Checked == true)
                {
                    sc.sAutoDate = "";
                    sc.sAutoTime = teSetting_Autotime.Text;
                }
                if (chkSetting_Weekly.Checked == true)
                {
                    sc.sAutoDate = deSetting_Autodate.Text;
                    sc.sAutoTime = teSetting_Autotime.Text;
                }
            }
            sc.Setting("BRM.config");

            AQFramework.Configurations conf = new AQFramework.Configurations("BRM.config", true);
            txtBackupFileName.Text = conf.ReadAppSettings("Name");
            txtBackupFilePath.Text = conf.ReadAppSettings("Default_path");
            txtBackupPassword.Text = conf.ReadAppSettings("Pass");

            txtBackupDB_ServerName.Text = conf.ReadAppSettings("Server_name");
            txtBackupDB_UserName.Text = conf.ReadAppSettings("User_name");
            txtBackupDB_UserPass.Text = conf.ReadAppSettings("User_pass");
            txtBackupDB_Database.Text = conf.ReadAppSettings("DB_name");
            MessageBox.Show("Thiết lập thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void simpleButton8_Click(object sender, EventArgs e)
        {
            lvRestore_BackupList.Items.Clear();
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\versionmanagement.xml");
            foreach (XmlElement xmlel in doc.GetElementsByTagName("Version"))
            {
                if (dpRestore_Date.Text == xmlel.Attributes["Date"].Value.ToString())
                {
                    ListViewItem liview = new ListViewItem(xmlel.Attributes["Name"].Value);
                    liview.SubItems.Add(xmlel.Attributes["Path"].Value);
                    liview.SubItems.Add(xmlel.Attributes["Date"].Value);
                    liview.SubItems.Add(xmlel.Attributes["Version"].Value);
                    lvRestore_BackupList.Items.Add(liview);
                }
            }
        }

        private void simpleButton12_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fdbr1 = new FolderBrowserDialog();
            fdbr1.ShowDialog();
            txtSetting_Path.Text = fdbr1.SelectedPath;
        }


        private void listView2_MouseClick(object sender, MouseEventArgs e)
        {       
            lvRestore_FileList.Items.Clear();
            VERSION vInfo = new VERSION();
            versionItems vi = new versionItems();
            if (lvRestore_BackupList.SelectedItems.Count > 0)
            {
                try
                {
                    vInfo = AQFramework.Utilities.Serializer<VERSION>.Load(lvRestore_BackupList.SelectedItems[0].SubItems[1].Text + "\\" + lvRestore_BackupList.SelectedItems[0].SubItems[0].Text + "-" + lvRestore_BackupList.SelectedItems[0].SubItems[3].Text + "info.xml");
                    vi = (versionItems)vInfo.versions[0];
                }
                catch (Exception)
                {
                    MessageBox.Show("Không tìm thấy file info-" + lvRestore_BackupList.SelectedItems[0].SubItems[0].Text + "-" + lvRestore_BackupList.SelectedItems[0].SubItems[3].Text + "info.xml", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                foreach (fileItems file in vi.detail.files)
                {
                    ListViewItem lsitem = new ListViewItem(file.path);
                    FileInfo fileicon = new FileInfo(file.path);
                    string checkDir = file.path.Replace(file.name, "");
                    DirectoryInfo dir = new DirectoryInfo(checkDir);
                    lsitem.Checked = true;
                    if (fileicon.Exists == true) lsitem.ImageIndex = 11;
                    if (fileicon.Exists == false) lsitem.ImageIndex = 10;
                    if (dir.Exists == false)
                    {
                        lsitem.ImageIndex = 9;
                        lsitem.Checked = false;
                    }
                    lsitem.SubItems.Add(file.name);
                    lvRestore_FileList.Items.Add(lsitem);
                }
                foreach (folderItems folder in vi.detail.folders)
                {
                    ListViewItem lsitem1 = new ListViewItem(folder.path+@"\");
                    DirectoryInfo foldericon = new DirectoryInfo(folder.path);
                    string checkDir = folder.path.Replace(folder.name, "");
                    DirectoryInfo dir = new DirectoryInfo(checkDir);
                    if (foldericon.Exists == true) lsitem1.ImageIndex = 11;
                    if (foldericon.Exists == false) lsitem1.ImageIndex = 10;
                    if (dir.Exists == false)
                    {
                        lsitem1.ImageIndex = 9;
                        lsitem1.Checked = false;
                    }
                    lsitem1.Checked = true;
                    lsitem1.SubItems.Add(folder.name+@"\");
                    lvRestore_FileList.Items.Add(lsitem1);
                }
            }
        }
        string sBk_dbdate;
        string sBk_dbtime;
        private void Do_backupdatabase()
        {
            string sDbname = txtBackupDB_Database.Text;
            string sUsername = txtBackupDB_UserName.Text;
            string sUserpass = txtBackupDB_UserPass.Text;
            string sName = txtBackupDB_ServerName.Text;

            string sBkdbdate = DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/" + DateTime.Now.Year.ToString();
            string sDb_name = txtBackupDB_Database.Text;
            string sFname = txtBackupDB_FileName.Text;
            string sBb_version = DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString();
            string sDb_path = txtBackupDB_FilePath.Text;

            FileInfo fexist = new FileInfo(txtBackupDB_FilePath.Text + "\\" + txtBackupDB_FileName.Text + ".bak");
            if (fexist.Exists == true) File.Delete(txtBackupDB_FilePath.Text + "\\" + txtBackupDB_FileName.Text + ".bak");
            try
            {
                BackupController c = new BackupController();
                c.BackupDatabase(sDbname, sUsername, sUserpass, sName, sDb_path + "\\" + txtBackupDB_FileName.Text + "-" + sBb_version + ".bak");
                c.Update_DBVersion(sDb_name, sFname, sBk_dbdate, sDb_path, sBk_dbdate, sBk_dbtime, Application.StartupPath + "\\versionmanagement.xml");
            }
            catch (Exception)
            {
                MessageBox.Show("Backup thất bại. Vui lòng kiểm tra thông tin nhập vào", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void simpleButton9_Click_1(object sender, EventArgs e)
        {
            DirectoryInfo fbackup = new DirectoryInfo(txtBackupDB_FilePath.Text);
            DriveInfo dinfo = new DriveInfo(fbackup.Root.ToString());
            lblInfoDB_fName.Text = fbackup.Root.ToString();
            long a = (dinfo.TotalSize) / (1024 * 1024 * 1024);
            progressBarControl2.Properties.Maximum = Convert.ToInt32(a);
            long la = (dinfo.TotalFreeSpace) / (1024 * 1024 * 1024);
            int ifree = Convert.ToInt32(la);

            lblInfoDB_Freespace.Text = ifree.ToString() + " MB";
            progressBarControl2.Position = progressBarControl2.Properties.Maximum - ifree;
            if (chkBackupDB_Auto.Checked == true)
            {
                if (radBackupDB_Monthly.Checked == true)
                {
                    sBk_dbdate = deBackupDB_AutoDate.Text;//Nguoi dung chon auto backup hang tuan
                    sBk_dbtime = teBackupDB_AutoTime.Text;
                    lblInfoDB_Descript.Text = "Backup tự động hàng tuần vào " + sBk_dbdate + " lúc " + sBk_dbtime;
                }
                if (radBackupDB_Daily.Checked == true)
                {
                    sBk_dbdate = "";//Nguoi dung chon auto backup hang ngay
                    sBk_dbtime = teBackupDB_AutoTime.Text;
                    lblInfoDB_Descript.Text = "Backup tự động hàng ngày lúc " + sBk_dbtime;
                }
            }
            else
            {
                sBk_dbdate = "";
                sBk_dbtime = "";
            }

            lblInfoDB_Name.Text = txtBackupDB_FileName.Text;
            lblInfoDB_Path.Text = txtBackupDB_FilePath.Text;
            lblInfoDB_Date.Text = DateTime.Now.ToShortDateString();

            string sDbname = txtBackupDB_Database.Text;
            string sUsername = txtBackupDB_UserName.Text;
            string sUserpass = txtBackupDB_UserPass.Text;
            string sName = txtBackupDB_ServerName.Text;

            string sFname = txtBackupDB_FileName.Text;
            string sDb_path = txtBackupDB_FilePath.Text;


            if (Check_DBInfo(sName, sUsername, sUserpass, sDbname, null, null) == true && Check_Info(sFname, sDb_path, null) == true)
            {
                pbProgress = new ProgressBar(1);
                pbProgress.Show(this);
                Thread bkdata = new Thread(new ThreadStart(Do_backupdatabase));
                tInfo.SelectedTabPage = xtraTabPage1;
                bkdata.Start();
            }
        }

        private void checkEdit6_CheckedChanged(object sender, EventArgs e)
        {
            if (chkBackupDB_Auto.Checked == true)
            {
                deBackupDB_AutoDate.Enabled = true;
                teBackupDB_AutoTime.Enabled = true;
                radBackupDB_Monthly.Enabled = true;
                radBackupDB_Daily.Enabled = true;
            }
            if (chkBackupDB_Auto.Checked == false)
            {
                deBackupDB_AutoDate.Enabled = false;
                teBackupDB_AutoTime.Enabled = false;
                radBackupDB_Monthly.Enabled = false;
                radBackupDB_Daily.Enabled = false;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
        }

        private void XtraForm1_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public bool Check_Info(string sfilename, string sfilepath, string spass)
        {
            ArrayList errorList = new ArrayList();
            string[] asChar = { "/", @"\", ":", "*", "?", "\"", "<", ">", "|" };
            foreach (string sChar in asChar)
            {
                if (sfilename.Contains(sChar) == true)
                {
                    errorList.Add("Tên file không được chứa các kí tự đặc biệt");
                }
            }
            if (sfilename == "")
            {
                errorList.Add("Chưa đặt tên file backup");
            }
            if (sfilepath == "")
            {
                errorList.Add("Chưa thiết lập đường dẫn lưu");
            }
            if (spass != null)
            {
                if (spass != "" && spass.Length < 6)
                {
                    errorList.Add("Password phải lớn hơn 6 kí tự");
                }
            }

            if (errorList.Count > 0)
            {
                StringBuilder message = new StringBuilder();

                // Concatenate errors into single message.
                for (int i = 0; i < errorList.Count; i++)
                {
                    message.Append(errorList[i]);
                    if (i + 1 < errorList.Count)
                    {
                        message.Append("\n");
                    }
                }
                showError(message.ToString());
                return false;
            }
            return true;
        }

        public bool Check_DBInfo(string sSevername, string sUsername, string sUserpass, string sDBname, string sDataPath, string sLogPath)
        {
            ArrayList errorList = new ArrayList();

            if (sSevername == "")
            {
                errorList.Add("Chưa nhập tên Server");

            }
            if (sUsername == "")
            {
                errorList.Add("Chưa nhập tên User");
            }
            if (sUserpass == "")
            {
                errorList.Add("Chưa nhập mật mã User");

            }
            if (sDBname == "")
            {
                errorList.Add("Chưa nhập tên Database");

            }
            if (sDataPath == "")
            {
                errorList.Add("Chưa chọn đường dẫn lưu file data");
            }
            if (sLogPath == "")
            {
                errorList.Add("Chưa chọn đường dẫn lưu file log");
            }

            if (errorList.Count > 0)
            {
                StringBuilder message = new StringBuilder();

                // Concatenate errors into single message.
                for (int i = 0; i < errorList.Count; i++)
                {
                    message.Append(errorList[i]);
                    if (i + 1 < errorList.Count)
                    {
                        message.Append("\n");
                    }
                }
                showError(message.ToString());
                return false;
            }
            return true;
        }

        private void showError(String message)
        {
            MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        string sDbname;
        string sDbpath;
        private void Do_RestoreDB()
        {
            string sServername = txtRestoreDB_ServerName.Text;
            string sUser = txtRestoreDB_UserName.Text;
            string sUserpass = txtRestoreDB_UserPass.Text;
            string sDatapath = txtRestoreDB_DataPath.Text;
            string sLogpath = txtRestoreDB_LogPath.Text;


            FileInfo datafile = new FileInfo(sDatapath + sDbname + ".mdf");
            FileInfo logfile = new FileInfo(sLogpath + sDbname + "_Log.ldf");
            if (datafile.Exists == false && logfile.Exists == false)
            {
                try
                {
                    RestoreController rc = new RestoreController();
                    rc.RestoreDatabase(sDbname, sDbpath, sServername, sUser, sUserpass, sDatapath, sLogpath);
                }
                catch (Exception)
                {
                    MessageBox.Show("Restore thất bại. Vui lòng kiểm tra thông tin nhập vào", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Database đã được restore tại đường dẫn chọn", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void simpleButton14_Click(object sender, EventArgs e)
        {
            string sServername = txtRestoreDB_ServerName.Text;
            string sUser = txtRestoreDB_UserName.Text;
            string sUserpass = txtRestoreDB_UserPass.Text;
            string sDatapath = txtRestoreDB_DataPath.Text;
            string sLogpath = txtRestoreDB_LogPath.Text;

            if (lvRestoreDB_BackupList.CheckedItems.Count > 0)
            {
                if (Check_DBInfo(sServername, sUser, sUserpass, null, sDatapath, sLogpath) == true)
                {
                    pbProgress = new ProgressBar(1);
                    pbProgress.Show(this);

                    Thread tRestoreDB = new Thread(new ThreadStart(Do_RestoreDB));
                    foreach (ListViewItem l4vitem in lvRestoreDB_BackupList.Items)
                    {
                        if (l4vitem.Checked == true)
                        {
                            sDbname = l4vitem.SubItems[0].Text;
                            sDbpath = l4vitem.SubItems[1].Text + "\\" + l4vitem.SubItems[3].Text + "-" + l4vitem.SubItems[4].Text + ".bak";
                            lblInfoRestoreDB_Date.Text = DateTime.Now.ToShortDateString();
                            lblInfoRestoreDB_Version.Text = l4vitem.SubItems[4].Text;
                            lblInfoRetoreDB_fName.Text = l4vitem.SubItems[3].Text;
                        }
                    }
                    tInfo.SelectedTabPage = xtraTabPage1;
                    tRestoreDB.Start();
                }
            }
            else
            {
                MessageBox.Show("Chưa chọn version cần restore", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void checkEdit7_CheckedChanged(object sender, EventArgs e)
        {
            if (chkBackupDB_ChangeConfig.Checked == true)
            {
                txtBackupDB_Database.Enabled = true;
                txtBackupDB_ServerName.Enabled = true;
                txtBackupDB_UserName.Enabled = true;
                txtBackupDB_UserPass.Enabled = true;
            }
            else
            {
                txtBackupDB_Database.Enabled = false;
                txtBackupDB_ServerName.Enabled = false;
                txtBackupDB_UserName.Enabled = false;
                txtBackupDB_UserPass.Enabled = false;
            }
        }

        private void simpleButton16_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fdbr2 = new FolderBrowserDialog();
            fdbr2.ShowDialog();
            txtBackupDB_FilePath.Text = fdbr2.SelectedPath;
        }

        private void checkEdit8_CheckedChanged(object sender, EventArgs e)
        {
            if (checkEdit8.Checked == true)
            {
                txtBackupDB_FileName.Enabled = true;
                //txtdbfpass.Enabled = true;
                txtBackupDB_FilePath.Enabled = true;
                meBackupDB_Description.Enabled = true;
            }
            else
            {
                txtBackupDB_FileName.Enabled = false;
                //txtdbfpass.Enabled = false;
                txtBackupDB_FilePath.Enabled = false;
                meBackupDB_Description.Enabled = false;
            }
        }

        private void simpleButton13_Click(object sender, EventArgs e)
        {
            lvRestoreDB_BackupList.Items.Clear();
            VERSIONMANAGEMENT dbver = AQFramework.Utilities.Serializer<VERSIONMANAGEMENT>.Load("versionmanagement.xml");

            foreach (versiondbinfo verit in dbver.versiondbinfo)
            {
                if (dpRestoreDB_Date.Text == verit.bkdbdate)
                {
                    ListViewItem liview = new ListViewItem(verit.dbname);
                    liview.SubItems.Add(verit.dbpath);
                    liview.SubItems.Add(verit.bkdbdate);
                    liview.SubItems.Add(verit.sfname);
                    liview.SubItems.Add(verit.db_version);
                    lvRestoreDB_BackupList.Items.Add(liview);
                }
            }
        }

        private void simpleButton17_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fdbr3 = new FolderBrowserDialog();
            fdbr3.ShowDialog();
            txtRestoreDB_DataPath.Text = fdbr3.SelectedPath + @"\";
        }

        private void simpleButton18_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fdbr4 = new FolderBrowserDialog();
            fdbr4.ShowDialog();
            txtRestoreDB_LogPath.Text = fdbr4.SelectedPath + @"\";
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            VERSIONMANAGEMENT dbver = AQFramework.Utilities.Serializer<VERSIONMANAGEMENT>.Load("versionmanagement.xml");
            VERSIONMANAGEMENT bklist = AQFramework.Utilities.Serializer<VERSIONMANAGEMENT>.Load("auto_backuplist.xml");

            //versioninfo fverinfo1 = new versioninfo();

            BackupController autob = new BackupController();

            foreach (versioninfo verit in dbver.versioninfo)
            {
                if (DateTime.Now.DayOfWeek.ToString() == verit.bkdate && DateTime.Now.ToShortTimeString() == verit.bktime)
                {

                    versioninfo fverinfo = new versioninfo();
                    fverinfo.name = verit.name;
                    fverinfo.path = verit.path;
                    fverinfo.sPassword = verit.sPassword;
                    fverinfo.bkdate = verit.bkdate;
                    fverinfo.version = verit.version;
                    fverinfo.bktime = verit.bktime;
                    bklist.versioninfo.Add(fverinfo);
                    AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(bklist, Application.StartupPath + "\\auto_backuplist.xml");

                }
                if (verit.bkdate == "" && DateTime.Now.ToShortTimeString() == verit.bktime)
                {
                    versioninfo fverinfo = new versioninfo();
                    fverinfo.name = verit.name;
                    fverinfo.path = verit.path;
                    fverinfo.sPassword = verit.sPassword;
                    fverinfo.bkdate = verit.bkdate;
                    fverinfo.bktime = verit.bktime;
                    fverinfo.version = verit.version;
                    bklist.versioninfo.Add(fverinfo);
                    AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(bklist, Application.StartupPath + "\\auto_backuplist.xml");

                }
            }

            foreach (versiondbinfo verit in dbver.versiondbinfo)
            {
                if (DateTime.Now.DayOfWeek.ToString() == verit.bk_dbdate && DateTime.Now.ToShortTimeString() == verit.bk_dbtime)
                {
                    versiondbinfo dbverinfo = new versiondbinfo();
                    dbverinfo.dbname = verit.dbname;
                    dbverinfo.dbpath = verit.dbpath;
                    dbverinfo.sfname = verit.sfname;
                    dbverinfo.bk_dbdate = verit.bk_dbdate;
                    dbverinfo.bk_dbtime = verit.bk_dbtime;
                    dbverinfo.db_version = verit.db_version;
                    bklist.versiondbinfo.Add(dbverinfo);
                    AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(bklist, Application.StartupPath + "\\auto_backuplist.xml");

                }
                if (verit.bk_dbdate == "" && DateTime.Now.ToShortTimeString() == verit.bk_dbtime)
                {
                    versiondbinfo dbverinfo = new versiondbinfo();
                    dbverinfo.dbname = verit.dbname;
                    dbverinfo.sfname = verit.sfname;
                    dbverinfo.dbpath = verit.dbpath;
                    dbverinfo.bk_dbdate = verit.bk_dbdate;
                    dbverinfo.bk_dbtime = verit.bk_dbtime;
                    bklist.versiondbinfo.Add(dbverinfo);
                    AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(bklist, Application.StartupPath + "\\auto_backuplist.xml");
                }
            }
        }

        private void checkEdit9_CheckedChanged(object sender, EventArgs e)
        {
            deBackupDB_AutoDate.Enabled = true;
        }

        private void checkEdit10_CheckedChanged(object sender, EventArgs e)
        {
            deBackupDB_AutoDate.Enabled = false;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            BackupController autob = new BackupController();
            RestoreController resc = new RestoreController();
            VERSIONMANAGEMENT bklist = AQFramework.Utilities.Serializer<VERSIONMANAGEMENT>.Load("auto_backuplist.xml");
            AQFramework.Configurations conf = new AQFramework.Configurations("BRM.config", true);

            for (int i = 0; i < bklist.versioninfo.Count; )
            {
                tmBackup.Stop();
                notifyIcon1.BalloonTipText = "Đang tiến hành backup tự động";
                notifyIcon1.ShowBalloonTip(3000);
                versioninfo verit = (versioninfo)bklist.versioninfo[i];
                string verdata = DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString();
                autob.Backup(verit.name + "-" + verdata, verit.path, resc.Decrypt(verit.sPassword, true), verit.path + "\\" + verit.name + "-" + verit.version + "info.xml");
                bklist.versioninfo.RemoveAt(i);
                AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(bklist, Application.StartupPath + "\\auto_backuplist.xml");

                FileInfo fCopiedFile = new FileInfo(verit.path + "\\" + verit.name + "-" + verdata + "info.xml");
                if (fCopiedFile.Exists == false)
                {
                    File.SetAttributes(fCopiedFile.FullName, FileAttributes.Normal);
                    fCopiedFile.CopyTo(verit.path + "\\" + verit.name + "-" + verdata + "info.xml", true);
                }
                autob.Update_Version(verit.name, DateTime.Now.ToShortDateString(), verit.path, resc.Decrypt(verit.sPassword, true), verit.bkdate, verit.bktime, Application.StartupPath + "\\versionmanagement.xml");
            }
            for (int i = 0; i < bklist.versiondbinfo.Count; )
            {
                tmBackup.Stop();
                notifyIcon1.BalloonTipText = "Đang tiến hành backup tự động";
                notifyIcon1.ShowBalloonTip(3000);
                versiondbinfo verit = (versiondbinfo)bklist.versiondbinfo[i];
                string sNewpath = verit.dbpath + "\\" + verit.sfname + "-" + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString() + ".bak";
                FileInfo fexist = new FileInfo(sNewpath);
                if (fexist.Exists == true) File.Delete(sNewpath);
                autob.BackupDatabase(verit.dbname, conf.ReadAppSettings("User_name"), conf.ReadAppSettings("User_pass"), conf.ReadAppSettings("Server_name"), sNewpath);
                bklist.versiondbinfo.RemoveAt(i);
                AQFramework.Utilities.Serializer<DataObjects.VERSIONMANAGEMENT>.Save(bklist, Application.StartupPath + "\\auto_backuplist.xml");
                autob.Update_DBVersion(verit.dbname, verit.sfname, DateTime.Now.ToShortDateString(), verit.dbpath, verit.bk_dbdate, verit.bk_dbtime, Application.StartupPath + "\\versionmanagement.xml");
            }
            tmBackup.Enabled = true;
        }

        private void checkEdit11_CheckedChanged(object sender, EventArgs e)
        {
            if (radBackup_Weekly.Checked == true)
            {
                deBackupAutoDate.Enabled = true;
            }
        }

        private void checkEdit12_CheckedChanged(object sender, EventArgs e)
        {
            if (radBackup_Daily.Checked == true)
            {
                deBackupAutoDate.Enabled = false;
            }
        }

        private void XtraForm1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void simpleButton7_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void simpleButton11_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void simpleButton15_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int a = txtBackupPassword.Text.Length;

                if (txtBackupPassword.Text.Length < 6)
                {
                    MessageBox.Show("Password không được nhỏ hơn 6 kí tự", "Thông báo");
                }
            }
        }

        private void txtpass_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int a = txtSetting_Pass.Text.Length;

                if (txtSetting_Pass.Text.Length < 6)
                {
                    MessageBox.Show("Password không được nhỏ hơn 6 kí tự", "Thông báo");
                }
            }
        }

        private void txtuser_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void lblpath_Click(object sender, EventArgs e)
        {

        }

        private void lblSetting_filename_Click(object sender, EventArgs e)
        {

        }

        private void chkSetting_daily_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSetting_daily.Checked == true) deSetting_Autodate.Enabled = false;
        }

        private void lvRestoreDB_BackupList_ItemChecked(object sender, ItemCheckedEventArgs e)
        {

        }

        private void lvRestoreDB_BackupList_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if ((ModifierKeys == Keys.Control) || (ModifierKeys == Keys.Shift))
            {
                e.NewValue = e.CurrentValue;
            }
            foreach (ListViewItem item in lvRestoreDB_BackupList.Items)
            {
                if (item.Index != e.Index)
                    item.Checked = false;
            }
        }

        private void lvRestore_FileList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {

        }

        private void lvRestore_FileList_ItemCheck(object sender, ItemCheckEventArgs e)
        {

        }

        private void lvRestore_FileList_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            foreach (ListViewItem item in lvRestore_FileList.Items)
            {
                if (item.ImageIndex == 9)
                    item.Checked = false;
            }
        }

        private void thayĐổiĐườngDẫnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderbr = new FolderBrowserDialog();
            folderbr.ShowDialog();

            foreach (ListViewItem ls in lvRestore_FileList.SelectedItems)
            {
                ls.Text = folderbr.SelectedPath + @"\" + ls.SubItems[1].Text;
                ls.ImageIndex = 10;
                ls.Checked = true;
            }
        }

        private void trvBackupChoose_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Checked == true)
            {
                if (e.Node.Nodes.Count > 0)
                {
                    //Calls the CheckAllChildNodes method, passing in the current 
                    //Checked value of the TreeNode whose checked state changed.
                    CheckAllChildNodes(e.Node, true);
                }
            }
        }
    }
}